package com.bytic.miaosha.rabbitmq;

import com.bytic.miaosha.constant.MQConstant;
import com.bytic.miaosha.domain.MiaoshaMessage;
import com.bytic.miaosha.domain.MiaoshaOrder;
import com.bytic.miaosha.domain.MiaoshaUser;
import com.bytic.miaosha.domain.OrderInfo;
import com.bytic.miaosha.exception.GlobalException;
import com.bytic.miaosha.result.CodeMsg;
import com.bytic.miaosha.service.GoodsService;
import com.bytic.miaosha.service.MiaoshaService;
import com.bytic.miaosha.service.OrderService;
import com.bytic.miaosha.utils.JsonUtils;
import com.bytic.miaosha.vo.GoodsVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MQReceive {

    private static Logger log = LoggerFactory.getLogger(MQReceive.class);

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private MiaoshaService miaoshaService;

    @RabbitListener(queues = MQConstant.MIAOSHA_QUEUE)
    public void receive(String message) {
        MiaoshaMessage miaoshaMessage = JsonUtils.stringToBean(message, MiaoshaMessage.class);
        log.info("receive message: " + message);
        MiaoshaUser user = miaoshaMessage.getUser();
        long goodsId = miaoshaMessage.getGoodsId();
        // 查看是否有库存
        GoodsVO goodsVO = goodsService.getGoodsVoByGoodsId(goodsId);
        if (goodsVO.getStockCount() <= 0) {
            throw new GlobalException(CodeMsg.MIAO_SHA_OVER);
        }
        // 查看是否重复秒杀
        MiaoshaOrder miaoshaOrder = orderService.getMiaoshaOrderByUserIdGoodsId(user.getId(), goodsId);
        if (miaoshaOrder != null) {
            throw new GlobalException(CodeMsg.REPEATE_MIAOSHA);
        }
        // 减库存 下订单 写入秒杀订单 ----> 事务
        miaoshaService.miaosha(user, goodsVO);
    }
}
